package logic

import (
	"cart_srv/carl"
	"context"
	"fmt"
	"goods_srv/goods"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCarlGoodsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddCarlGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCarlGoodsLogic {
	return &AddCarlGoodsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddCarlGoodsLogic) AddCarlGoods(req *types.AddCreateRequest) (resp *types.RegMsgResponse, err error) {
	// todo: 添加购物车
	//模拟用户登录 UserID
	userId := 1

	//判断商品是否存在
	detail, err := l.svcCtx.GoodsSrv.GoodsDetail(l.ctx, &goods.GoodsDetailRequest{GoodsId: req.GoodsId})
	if err != nil {
		return &types.RegMsgResponse{
			Code: -1,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}

	if detail.GoodsID == 0 {
		return &types.RegMsgResponse{
			Code: -1,
			Msg:  "商品不存在",
		}, err
	}

	//判断库存是否充足
	stock, _ := l.svcCtx.GoodsSrv.GetGoodsStock(l.ctx, &goods.GetGoodsStockRequest{GoodsId: req.GoodsId})

	fmt.Println("获取到的库存", stock.GoodsStock)

	if stock.GoodsStock < req.Num {
		return &types.RegMsgResponse{
			Code: -2,
			Msg:  "商品库存不足",
		}, err
	}
	//添加购物车
	addCarl, err := l.svcCtx.CarlSrv.AddCarl(l.ctx, &carl.AddCarlRequest{
		GoodsId:    detail.GoodsID,
		UserId:     int64(userId),
		GoodsTitle: detail.GoodsTitle,
		GoodsPrice: detail.GoodsPrice,
		Num:        req.Num,
	})
	if err != nil {
		return &types.RegMsgResponse{
			Code: -1,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}

	return &types.RegMsgResponse{
		Code: 0,
		Msg:  "添加成功",
		Data: map[string]interface{}{
			"carlId": addCarl.CarlId,
		},
	}, err
}
